<!-- 数据导出服务 -->
<template>
  <v-card>
    <v-card-title>表格数据导出Excel功能</v-card-title>
    <v-card-subtitle>
      <p>组件：sheetJs(js-xlsx)</p>
      <p>官网：<a href="https://sheetjs.com/demos/table.html">https://sheetjs.com/demos/table.html</a> </p>
    </v-card-subtitle>
     <v-card-text>
       <v-text-field label="导出文件名称" v-model="filename"></v-text-field>
       <v-data-table
       :headers="headers"
       hide-default-footer
      :items="tableItems"></v-data-table>
     <!-- todo -->
    </v-card-text>
    <v-card-actions>
      <v-btn color="primary" @click="exportData">导出</v-btn>
    </v-card-actions>
  </v-card>
</template>

<script>
import XLSX from 'xlsx'
export default {
  name: 'XlsxExport',
  components: {},
  data: function () {
    return {
      headers: [
        { text: 'ID', value: 'id', width: 80 },
        { text: '名称', value: 'name' },
        { text: '标题', value: 'title' },
        { text: '时间', value: 'createdAt' }
      ],
      tableItems: [
        { id: 1, name: '1测试名称1', title: '1测试1标题1', createdAt: '2020-01-01 23:21:11' },
        { id: 2, name: '2测试名称2', title: '2测试2标题2', createdAt: '2020-01-01 23:21:22' },
        { id: 3, name: '3测试名称3', title: '3测试3标题3', createdAt: '2020-01-01 23:21:33' },
        { id: 4, name: '4测试名称4', title: '4测试4标题4', createdAt: '2020-01-01 23:21:44' },
        { id: 5, name: '5测试名称5', title: '5测试5标题5', createdAt: '2020-01-01 23:21:55' },
        { id: 6, name: '6测试名称6', title: '6测试6标题6', createdAt: '2020-01-01 23:21:66' },
        { id: 7, name: '7测试名称7', title: '7测试7标题7', createdAt: '2020-01-01 23:21:77' }
      ],
      filename: 'out.xlsx'
    }
  },
  created: function () {

  },
  computed: {},
  methods: {
    exportData: function() {
      let workbook = XLSX.utils.book_new()
      let worksheetName = 'text'
      let worksheetData = [['序号', '标题', '名称', '时间']]
      this.tableItems.forEach(e => {
        worksheetData.push([ e.id, e.title, e.name, e.createdAt ])
      })
      var worksheet = XLSX.utils.aoa_to_sheet(worksheetData)
      XLSX.utils.book_append_sheet(workbook, worksheet, worksheetName)
      // workbook不可为空
      XLSX.writeFile(workbook, this.filename)
    }
  }
}
</script>
<style scoped>
</style>
